<?php

namespace App\Services\AetherUpload;

use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\Response;

class UploadController extends \App\Http\Controllers\Controller
{
    protected $uploadService;

    public function __construct(AetherUploadService $uploadService)
    {
        $this->uploadService = $uploadService;
    }

    public function preprocess()
    {
        $this->validate(request(), [
            'resource_name' => 'required',
            'resource_size' => 'required',
            'group'         => 'required',
            'resource_hash' => 'present',
        ]);

        $resourceName = Request::input('resource_name');
        $resourceSize = Request::input('resource_size');
        $resourceHash = Request::input('resource_hash');
        $group = Request::input('group');
        return $this->uploadService->preprocess($resourceName, $resourceSize, $resourceHash, $group);
    }

    public function saveChunk(): JsonResponse
    {
        $this->validate(request(), [
            'chunk_total'            => 'required',
            'chunk_index'            => 'required',
            'resource_temp_basename' => 'required',
            'resource_ext'           => 'required',
            'resource_chunk'         => 'required',
            'group_subdir'           => 'required',
            'group'                  => 'required',
            'resource_hash'          => 'present',
        ]);

        $chunkTotalCount = Request::input('chunk_total');
        $chunkIndex = Request::input('chunk_index');
        $resourceTempBaseName = Request::input('resource_temp_basename');
        $resourceExt = Request::input('resource_ext');
        $chunk = Request::file('resource_chunk');
        $groupSubDir = Request::input('group_subdir');
        $resourceHash = Request::input('resource_hash');
        $group = Request::input('group');
        return $this->uploadService->saveChunk($chunkTotalCount, $chunkIndex, $resourceTempBaseName, $resourceExt, $chunk, $groupSubDir, $resourceHash, $group);
    }

    /**
     * Handle the request of option method in CORS
     * @return ResponseFactory|Response
     */
    public function options()
    {
        return response('');
    }


}
